<template>
  <t-modal
    :title="title"
    width="1048px"
    :visible="visible"
    @cancel="closeModal()"
    @ok="onSubmit()"
    wrapClassName="add-modal-container"
    v-bind="footer"
    forceRender
    :confirmLoading="submitLoading"
  >
    <div class="curve-modal-body">
      <a-form-model
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :hideRequiredMark="false"
      >
        <!-- 新增、编辑数据 -->
        <div class="sub-title" v-if="operateType == 4">基本信息</div>
        <a-row :gutter="0">
          <a-col :span="12">
            <a-form-model-item
              label="样板名称"
              prop="name"
              :rules="{
                required: operateType == 4 || operateType == 3 ? false : true,
                message: '请输入样板名称',
              }"
            >
              <a-input
                v-model="form.name"
                :disabled="isDisabled"
                placeholder="请输入"
              ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item
              label="专业"
              prop="major"
              :rules="{
                required: operateType == 4 || operateType == 3 ? false : true,
                message: '请选择专业',
              }"
            >
              <a-select
                placeholder="请选择"
                v-model="form.major"
                showSearch
                :filter-option="filterOption"
                :disabled="isDisabled"
              >
                <a-select-option
                  :value="item.dicItemCode"
                  v-for="item in majorSource"
                  :key="item.uuid"
                >
                  {{ item.dicItemName }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-form-model-item
          label="样板照片"
          prop="image"
          :rules="{
            required: operateType == 4 || operateType == 3 ? false : true,
            message: '请选择样板照片',
          }"
        >
          <bjUploadImg
            :viewMode="isDisabled"
            :count="20"
            v-model="form.image"
            @change="upLoadImage($event)"
            replaceField="url"
          ></bjUploadImg>
        </a-form-model-item>

        <a-form-model-item
          label="技术说明"
          prop="technicalDescription"
          :rules="{
            required: operateType == 4 || operateType == 3 ? false : true,
            message: '请选择技术说明',
          }"
        >
          <bjUploadFile
            :viewMode="isDisabled"
            :count="20"
            v-model="form.technicalDescription"
            @preview="viewFile($event)"
            @download="downloadFile($event)"
            @change="handleUpLoadFile($event, 'technicalDescription')"
            :replaceFields="{
              fileName: 'fileName',
              fileSize: 'fileSize',
              fileType: 'fileType',
            }"
          ></bjUploadFile>
        </a-form-model-item>
        <a-form-model-item
          label="材料证明"
          prop="materialProof"
          :rules="{
            required: operateType == 4 || operateType == 3 ? false : true,
            message: '请选择材料证明',
          }"
        >
          <bjUploadFile
            :viewMode="isDisabled"
            :count="20"
            v-model="form.materialProof"
            @preview="viewFile($event)"
            @download="downloadFile($event)"
            @change="handleUpLoadFile($event, 'materialProof')"
            :replaceFields="{
              fileName: 'fileName',
              fileSize: 'fileSize',
              fileType: 'fileType',
            }"
          ></bjUploadFile>
        </a-form-model-item>
        <a-row :gutter="0">
          <a-col :span="12">
            <a-form-model-item label="提交人">
              <a-input v-model="form.creator" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="提交时间">
              <a-input v-model="form.createTime" disabled></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-form-model-item label="备注">
          <a-textarea
            placeholder="请输入"
            :rows="4"
            v-model="form.remark"
            :disabled="isDisabled"
          />
        </a-form-model-item>
        <!-- 审批数据 -->
        <template v-if="operateType == 4">
          <div class="sub-title">审批信息</div>
          <a-form-model-item
            label="审批结果"
            prop="operate"
            :rules="{
              required: true,
              message: '请选择审批结果',
            }"
          >
            <a-radio-group v-model="form.operate">
              <a-radio :value="2">
                通过
              </a-radio>
              <a-radio :value="3">
                驳回
              </a-radio>
            </a-radio-group>
          </a-form-model-item>
          <a-form-model-item label="审批意见" prop="reason">
            <a-textarea placeholder="请输入" :rows="4" v-model="form.reason" />
          </a-form-model-item>
        </template>
      </a-form-model>
    </div>
    <!-- 附件预览弹窗 -->
    <previewModal
      ref="previewModal"
      :visible.sync="previewModal.visible"
      :loading="previewModal.loading"
    ></previewModal>
  </t-modal>
</template>

<script>
import { mapGetters } from "vuex";
import { axios } from "@/utils/request";
import { getToken, downloadDfs } from "@/utils/TopVUI";
//附件上传
import bjUploadFile from "@/components/extendCustom/bj-upload-file";
//上传图片
import bjUploadImg from "@/components/extendCustom/bj-upload-img";
//预览
import previewModal from "@/pages/document/minio/previewModal";
import { getDicItemByCode } from "@/api/common.js";
import { getNowDateStr } from "@/utils/util";
export default {
  components: {
    bjUploadFile,
    previewModal,
    bjUploadImg,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    operateType: {
      type: [String, Number],
      default: 1,
    },
    parameter: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      title: "新增",
      footer: {},
      isDisabled: false,
      submitLoading: false,
      //预览
      previewModal: {
        visible: false,
        loading: false,
      },
      form: {
        uuid: "",
        //名称
        name: "",
        //方案类型
        major: undefined,
        //照片
        image: [],
        //技术说明
        technicalDescription: [],
        //材料证明
        materialProof: [],
        //提交人
        creator: "",
        //提交时间
        createTime: "",
        //备注
        remark: "",
        //审批结果
        operate: "",
        //审批意见
        reason: "",
      },
      rules: {},
      //专业
      majorSource: [],
    };
  },
  computed: {
    ...mapGetters(["configData", "nickname"]),
    kkFileView() {
      let index = this.configData.findIndex(
        (item) => item.code === "kkFileView"
      );
      if (index >= 0) {
        return this.configData[index].value;
      } else {
        return "http://192.168.1.216:8012/onlinePreview";
      }
    },
  },
  watch: {
    visible: {
      handler(val) {
        if (val) {
          this.getData();
        }
      },
      immediate: true,
    },
  },

  methods: {
    //查询数据
    async getData() {
      await this.filterTitle();
      //方案类型
      this.majorSource = await this.getDicCodeData("major");
      //详情
      if (this.operateType != 1) {
        this.getDetail();
      } else {
        this.form.creator = this.nickname;
        this.form.createTime = getNowDateStr(2);
      }
    },

    //查询字典表
    getDicCodeData(dicCode = "") {
      return new Promise((resolve, reject) => {
        getDicItemByCode({ code: dicCode })
          .then((res) => {
            let { data } = res;
            resolve(data);
          })
          .catch((_) => {
            reject();
          })
          .finally((_) => {});
      });
    },

    //
    filterTitle() {
      let { operateType } = this;
      switch (operateType) {
        case 1:
          this.title = "新增";
          this.footer = {};
          this.isDisabled = false;
          break;

        case 2:
          this.title = "编辑";
          this.footer = {};
          this.isDisabled = false;
          break;

        case 3:
          this.title = "详情";
          this.footer = { footer: null };
          this.isDisabled = true;
          break;

        case 4:
          this.title = "审批";
          this.footer = {};
          this.isDisabled = true;
          break;

        default:
          break;
      }
    },

    onSubmit() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          let { operateType } = this;
          //审批
          if (operateType == 4) {
            this.approveFormData();
          }
          //新增、编辑
          else {
            this.saveFormData();
          }
        }
      });
    },

    //审批
    approveFormData() {
      let { form } = this;
      let formJson = {
        //ID
        uuid: form.uuid,
        //审批结果
        operate: form.operate,
        //审批意见
        reason: form.reason,
      };
      this.submitLoading = true;
      axios
        .post(
          `/probusiness/technologyConstructionSample/approveData`,
          formJson,
          {
            headers: {
              "Content-Type": "application/json",
            },
          }
        )
        .then((res) => {
          if (res.statusCode === 200 || res === 1) {
            this.$message.success(res.message ?? "审批成功", 1.5);
            this.closeModal();
            this.$parent.getTableData();
          } else {
            this.$message.error(res?.message ?? "审批失败");
          }
        })
        .catch((_) => {
          this.$message.error(_?.message ?? "审批失败");
        })
        .finally((_) => {
          this.submitLoading = false;
        });
    },

    //新增、编辑
    saveFormData() {
      let { form } = this;
      const files_1 = form.technicalDescription.map(
        ({ $$DataType, file, loading, ...keepAttrs }) => keepAttrs
      );
      const files_2 = form.materialProof.map(
        ({ $$DataType, file, loading, ...keepAttrs }) => keepAttrs
      );
      const images = form.image.map(
        ({ $$DataType, file, loading, ...keepAttrs }) => keepAttrs
      );
      let formJson = {
        //名称
        name: form.name,
        //方案类型
        major: form.major,
        //照片
        image: JSON.stringify(images),
        //技术说明
        technicalDescription: JSON.stringify(files_1),
        //材料证明
        materialProof: JSON.stringify(files_2),
        //备注
        remark: form.remark,
      };
      //编辑
      if (form.uuid) {
        formJson.uuid = form.uuid;
      }
      this.submitLoading = true;
      axios
        .post(
          `/probusiness/technologyConstructionSample/saveOrUpdateData`,
          formJson,
          {
            headers: {
              "Content-Type": "application/json",
            },
          }
        )
        .then((res) => {
          if (res.statusCode === 200 || res === 1) {
            this.$message.success("操作成功", 1.5);
            this.closeModal();
            this.$parent.getTableData();
          } else {
            this.$message.error(res?.message ?? "操作失败");
          }
        })
        .catch((_) => {})
        .finally((_) => {
          this.submitLoading = false;
        });
    },

    //下载
    downloadFile(row) {
      let { url } = row;
      downloadDfs(url);
    },

    //预览
    viewFile(file) {
      let { url } = file;
      this.previewModal.loading = true;
      this.$refs.previewModal.type = "file";
      this.$refs.previewModal.fileUrl =
        this.kkFileView +
        "/onlinePreview?url=" +
        encodeURIComponent(Base64.encode(url)) +
        "&watermarkTxt=" +
        //水印内容
        encodeURIComponent("") +
        "&token=" +
        getToken();
      this.previewModal.visible = true;
      this.previewModal.loading = false;
    },

    //上传图片
    upLoadImage({ file, index }) {
      let formData = new FormData();
      formData.append("bucket", "yx-cloud-vue");
      formData.append("file", file);
      this.$set(this.form["image"][index], "loading", true);
      axios
        .post(`/document/minio/uploadfile`, formData, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        })
        .then((res) => {
          this.$set(this.form["image"][index], "uid", res.dfsFileUuid);
          this.$set(this.form["image"][index], "url", res.url);
          this.$set(this.form["image"][index], "fileName", file.name);
        })
        .catch((_) => {
          this.$set(this.form["image"][index], "fail", true);
        })
        .finally((_) => {
          this.$set(this.form["image"][index], "loading", false);
        });
    },

    //上传附件
    handleUpLoadFile({ file, index }, domain) {
      let formData = new FormData();
      formData.append("bucket", "yx-cloud-vue");
      formData.append("file", file);
      this.$set(this.form[domain][index], "loading", true);
      axios
        .post(`/document/minio/uploadfile`, formData, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        })
        .then((res) => {
          this.$set(this.form[domain][index], "dfsFileUuid", res.dfsFileUuid);
          this.$set(this.form[domain][index], "url", res.url);
        })
        .catch((_) => {
          this.$set(this.form[domain][index], "fail", true);
        })
        .finally((_) => {
          this.$set(this.form[domain][index], "loading", false);
        });
    },

    //详情
    getDetail() {
      let { uuid } = this.parameter;
      axios
        .post(
          `/probusiness/technologyConstructionSample/getDetailByUuid?uuid=${uuid}`,
          {},
          {
            headers: {
              "Content-Type": "application/json",
            },
          }
        )
        .then((res) => {
          let { data } = res;
          this.form = {
            uuid: data?.uuid,
            //名称
            name: data?.name,
            //方案类型
            major: data?.major,
            //照片
            image: JSON.parse(data?.image ?? "[]"),
            //技术说明
            technicalDescription: JSON.parse(
              data?.technicalDescription ?? "[]"
            ),
            //材料证明
            materialProof: JSON.parse(data?.materialProof ?? "[]"),
            //提交人
            creator: data?.creator,
            //提交时间
            createTime: data?.createTime,
            //备注
            remark: data?.remark,
            //审批结果
            operate: "",
            //审批意见
            reason: "",
          };
        })
        .catch((_) => {});
    },

    //重置表单
    resetForm() {
      this.form = {
        uuid: "",
        //名称
        name: "",
        //方案类型
        major: undefined,
        //照片
        image: [],
        //技术说明
        technicalDescription: [],
        //材料证明
        materialProof: [],
        //提交人
        creator: "",
        //提交时间
        createTime: "",
        //备注
        remark: "",
        //审批结果
        operate: "",
        //审批意见
        reason: "",
      };
      this.$refs.ruleForm.clearValidate();
    },

    //关闭
    closeModal() {
      this.resetForm();
      this.$emit("update:visible", false);
    },

    //select 搜索过滤
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
  },
};
</script>

<style lang="less" scoped>
/deep/.add-modal-container {
  .ant-modal-body {
    padding: 0 !important;
    .curve-modal-body {
      box-sizing: border-box;
      padding: 14px 70px 14px 40px;
      max-height: 700px;
      overflow: auto;
      .ant-form-item {
        display: flex;
        .ant-form-item-label {
          flex-shrink: 0;
          width: 140px;
          label {
            color: #333333;
          }
        }
        .ant-form-item-control-wrapper {
          flex: 1;
          overflow: hidden;
        }
      }
      .bj-upload-file {
        .choosed-file-warp {
          width: 100%;
        }
      }
      .sub-title {
        padding-left: 30px;
        font-family: Microsoft YaHei;
        font-weight: 400;
        font-size: 18px;
        color: #525a5d;
        position: relative;
        margin-bottom: 10px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        &::after {
          content: "";
          width: 3px;
          height: 16px;
          background: #1890ff;
          position: absolute;
          left: 14px;
          top: 50%;
          transform: translateY(-50%);
        }
        .ant-btn {
          margin-right: 0;
        }
      }
    }
  }
}
</style>
